package com.cloud.xtools.user.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.cloud.xtools.user.domain.entity.Role;
import com.cloud.xtools.user.domain.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @author Daixinguo
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {

    @Select("SELECT * FROM users ${ew.customSqlSegment}")
    @Results({
            // 这里 id 需要显式映射一下才行，自动映射有时可能会因为某些配置或特殊情况而失效
            @Result(property = "id", column = "id"),
            // 默认自动映射，当前属性名与数据库字段名一致时，可以省略
            // @Result(property = "username", column = "username"),
            // 关联角色
            @Result(property = "roles",
                    javaType = List.class,
                    // 指定用于关联查询的列，这里是 User 实体的 id 列
                    column = "id",
                    many = @Many(select = "selectRolesByUserId"))
    })
    // List<User> userList(@Param("ew") Wrapper<User> wrapper);
    List<User> userList(@Param(Constants.WRAPPER) Wrapper<User> wrapper);

    // 查询角色
    @Select("SELECT * FROM roles WHERE id IN (SELECT role_id FROM user_roles WHERE user_id = #{userId})")
    List<Role> selectRolesByUserId(Long userId);

}
